package com.blensmile.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.blensmile.App;

/**
 * Created by talkmate-10 on 2016/7/21.
 */
public class AutoMediaPlayer extends MediaPlayer implements AudioManager.OnAudioFocusChangeListener {

    private AudioManager mgr;
    private OnAudioMediaPlayerFoucusChanged callBack;

    public AutoMediaPlayer(){
        MediaPlayer mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    public AutoMediaPlayer(OnAudioMediaPlayerFoucusChanged callBack ){
        this();
        this.callBack = callBack;
    }

    @Override
    public void start() throws IllegalStateException {
        super.start();
        if(mgr == null){
            mgr = (AudioManager) App.app.getSystemService(Context.AUDIO_SERVICE);
        }
        mgr.requestAudioFocus(AutoMediaPlayer.this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    }

    @Override
    public void release() {
        if(mgr != null){
            mgr.abandonAudioFocus(AutoMediaPlayer.this);
            mgr = null;
        }
        super.release();
    }

    @Override
    public void stop() throws IllegalStateException {
        if(mgr != null){
            mgr.abandonAudioFocus(AutoMediaPlayer.this);
        }
        super.stop();
    }

    @Override
    public  void onAudioFocusChange(int focusChange){
        if(callBack != null){
            callBack.onMediaFoucusChanged(focusChange);
        }
    }

    public void setOnAuodioMediaPlayerFoucusChangedListener(OnAudioMediaPlayerFoucusChanged callBack){
        this.callBack = callBack;
    }

    public interface OnAudioMediaPlayerFoucusChanged{
        void onMediaFoucusChanged(int foucusChanged);
    }

    @Override
    protected void finalize() {
        super.finalize();
        LogUtils.e("Finalized","id:"+hashCode());
    }
}
